//
//  MMZCViewController.m
//  MMR
//
//  Created by qianfeng on 15/6/30.
//  Copyright © 2015年 MaskMan. All rights reserved.
//

#import "MMZCViewController.h"
//#import "forgetPassWardViewController.h"
//#import "AppDelegate.h"
//#import "MMZCHMViewController.h"
#import "HomeViewController.h"
#import "RTRootNavigationController.h"
#import "AFOAuthCredential.h"
#import "GROAuth2SessionManager.h"

//offline问题
#import "RouteViewController.h"
#import "ChangeShiftViewController.h"
#import "SpotTaskViewController.h"
#import "AuditViewController.h"
#import "SopViewController.h"
#import "AuditGeneralViewController.h"
#import "UserSites.h"
#import "PointModelOffline.h"
#import "LineDetailOffline.h"
#import "AuditCategoryOffline.h"
#import "SopModel.h"
#import "PointValueModel.h"
#import "ShiftModel.h"
#import "AuditCategory.h"
#import "MenuRole.h"
#import "HomeBaseViewController.h"
#import "WorkOrderModelCopy.h"

#define height_add 350
@interface MMZCViewController ()
{
    UIImageView *View;
    UIView *bgView;
    UITextField *pwd;
    UITextField *user;
    UIButton *QQBtn;
    UIButton *weixinBtn;
    UIButton *xinlangBtn;
}
@property(copy,nonatomic) NSString * accountNumber;
@property(copy,nonatomic) NSString * mmmm;
@property(copy,nonatomic) NSString * user;


@end

@implementation MMZCViewController
static MMZCViewController *mmzvc = nil;

+ (instancetype)share {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mmzvc = [[self alloc] init];
    });
    return mmzvc;
}
-(void)viewWillAppear:(BOOL)animated
{
    //[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:216/255.0f green:209/255.0f blue:192/255.0f alpha:1]];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //self.view.backgroundColor=[UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1];
    //设置NavigationBar背景颜色
    View=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    //View.backgroundColor=[UIColor redColor];
    View.image=[UIImage imageNamed:@"Login"];
    [self.view addSubview:View];
    
    ////    self.title=@"登陆";
    ////    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(clickaddBtn:)];
    ////    [addBtn setImage:[UIImage imageNamed:@"goback_back_orange_on"]];
    ////    [addBtn setImageInsets:UIEdgeInsetsMake(0, -15, 0, 15)];
    ////    addBtn.tintColor=[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1];
    ////    [self.navigationItem setLeftBarButtonItem:addBtn];
    //
    //    UIBarButtonItem *right=[[UIBarButtonItem alloc]initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(zhuce)];
    //    right.tintColor=[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1];
    //    self.navigationItem.rightBarButtonItem=right;
    
    //为了显示背景图片自定义navgationbar上面的三个按钮
    UIButton *but =[[UIButton alloc]initWithFrame:CGRectMake(5, 27, 35, 35)];
    [but setImage:[UIImage imageNamed:@"goback_back_orange_on"] forState:UIControlStateNormal];
    [but addTarget:self action:@selector(clickaddBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:but];
    
    UIButton *zhuce =[[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-60, 30+height_add, 50, 30)];
    [zhuce setTitle:@"注册" forState:UIControlStateNormal];
    [zhuce setTitleColor:[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1] forState:UIControlStateNormal];
    zhuce.font=[UIFont systemFontOfSize:17];
    [zhuce addTarget:self action:@selector(zhuce) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:zhuce];
    
    
    UILabel *lanel=[[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width-30)/2, 30+height_add, 50, 30)];
    lanel.text=@"登录";
    lanel.textColor=[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1];
    //    [self.view addSubview:lanel];
    
    
    [self createButtons];
    //    [self createImageViews];
    [self createTextFields];
    
    //    [self createLabel];
}

-(void)clickaddBtn:(UIButton *)button
{
    //      [kAPPDelegate appDelegateInitTabbar];
    self.view.backgroundColor=[UIColor whiteColor];
    exit(0);
}


-(void)createLabel
{
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width-140)/2, 390, 140, 21)];
    label.text=@"第三方账号快速登录";
    label.textColor=[UIColor grayColor];
    label.textAlignment=UITextAlignmentCenter;
    label.font=[UIFont systemFontOfSize:14];
    [self.view addSubview:label];
}

-(void)createTextFields
{
    CGRect frame=[UIScreen mainScreen].bounds;
    bgView=[[UIView alloc]initWithFrame:CGRectMake(10, 75+height_add, frame.size.width-20, 100)];
    if (IS_IPHONE_5) {
        bgView=[[UIView alloc]initWithFrame:CGRectMake(10, 15+height_add, frame.size.width-20, 100)];
    }
    bgView.layer.cornerRadius=3.0;
    bgView.alpha=0.7;
    bgView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:bgView];
    
    user=[self createTextFielfFrame:CGRectMake(60, 10, 271, 30) font:[UIFont systemFontOfSize:14] placeholder:@"请输入用户名"];
    //user.text=@"13419693608";
    //    user.keyboardType=UIKeyboardTypeNumberPad;
    user.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    pwd=[self createTextFielfFrame:CGRectMake(60, 60, 271, 30) font:[UIFont systemFontOfSize:14]  placeholder:@"请输入密码" ];
    pwd.clearButtonMode = UITextFieldViewModeWhileEditing;
    //pwd.text=@"123456";
    //密文样式
    pwd.secureTextEntry=YES;
    //pwd.keyboardType=UIKeyboardTypeNumberPad;
    
    
    UIImageView *userImageView=[self createImageViewFrame:CGRectMake(20, 10, 25, 25) imageName:@"login_icon_username" color:nil];
    UIImageView *pwdImageView=[self createImageViewFrame:CGRectMake(20, 60, 25, 25) imageName:@"login_icon_password" color:nil];
    UIImageView *line1=[self createImageViewFrame:CGRectMake(20, 50, bgView.frame.size.width-40, 1) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    UIImageView *line=[self createImageViewFrame:CGRectMake(20, 100, bgView.frame.size.width-40, 1) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    [bgView addSubview:user];
    [bgView addSubview:pwd];
    
    [bgView addSubview:userImageView];
    [bgView addSubview:pwdImageView];
    [bgView addSubview:line1];
    [bgView addSubview:line];
    
//    user.text=@"ney01";
//    pwd.text=@"111111";
}


-(void)touchesEnded:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
{
    [user resignFirstResponder];
    [pwd resignFirstResponder];
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [user resignFirstResponder];
    [pwd resignFirstResponder];
}

-(void)createImageViews
{
    //    UIImageView *userImageView=[self createImageViewFrame:CGRectMake(25, 10, 25, 25) imageName:@"ic_landing_nickname" color:nil];
    //    UIImageView *pwdImageView=[self createImageViewFrame:CGRectMake(25, 60, 25, 25) imageName:@"ic_landing_password" color:nil];
    //    UIImageView *line1=[self createImageViewFrame:CGRectMake(25, 50, 260, 1.5) imageName:nil color:[UIColor lightGrayColor]];
    //
    //    //UIImageView *line2=[self createImageViewFrame:CGRectMake(88, 210, 280, 1) imageName:nil color:[UIColor grayColor]];
    
    UIImageView *line3=[self createImageViewFrame:CGRectMake(2, 400, 100, 1) imageName:nil color:[UIColor lightGrayColor]];
    UIImageView *line4=[self createImageViewFrame:CGRectMake(self.view.frame.size.width-100-4, 400, 100, 1) imageName:nil color:[UIColor lightGrayColor]];
    
    //    [bgView addSubview:userImageView];
    //    [bgView addSubview:pwdImageView];
    //    [bgView addSubview:line1];
    //[self.view addSubview:line2];
    [self.view addSubview:line3];
    [self.view addSubview:line4];
    
}


-(void)createButtons
{
    UIButton *landBtn=[self createButtonFrame:CGRectMake(10, 190+height_add, self.view.frame.size.width-20, 74) backImageName:@"login_button" title:nil titleColor:[UIColor blackColor]  font:[UIFont systemFontOfSize:19] target:self action:@selector(landClick)];
    //    landBtn.backgroundColor=[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1];
    if (IS_IPHONE_5) {
        landBtn=[self createButtonFrame:CGRectMake(10, 130+height_add, self.view.frame.size.width-20, 74) backImageName:@"login_button" title:nil titleColor:[UIColor blackColor]  font:[UIFont systemFontOfSize:19] target:self action:@selector(landClick)];
    }
    landBtn.imageEdgeInsets = UIEdgeInsetsMake(10, (SCREEN_WIDTH- 124), 10, 50);
    landBtn.backgroundColor=[UIColor whiteColor];
    landBtn.layer.cornerRadius=5.0f;
    
    UIButton *newUserBtn=[self createButtonFrame:CGRectMake(5, 235+height_add, 70, 30) backImageName:nil title:@"快速注册" titleColor:[UIColor grayColor] font:[UIFont systemFontOfSize:13] target:self action:@selector(registration:)];
    //newUserBtn.backgroundColor=[UIColor lightGrayColor];
    
    UIButton *forgotPwdBtn=[self createButtonFrame:CGRectMake(self.view.frame.size.width-75, 235+height_add, 60, 30) backImageName:nil title:@"找回密码" titleColor:[UIColor grayColor] font:[UIFont systemFontOfSize:13] target:self action:@selector(fogetPwd:)];
    //fogotPwdBtn.backgroundColor=[UIColor lightGrayColor];
    
    
#define Start_X 60.0f           // 第一个按钮的X坐标
#define Start_Y 440.0f           // 第一个按钮的Y坐标
#define Width_Space 50.0f        // 2个按钮之间的横间距
#define Height_Space 20.0f      // 竖间距
#define Button_Height 50.0f    // 高
#define Button_Width 50.0f      // 宽
    
    
    
    //微信
    weixinBtn=[[UIButton alloc]initWithFrame:CGRectMake((self.view.frame.size.width-50)/2, 440, 50, 50)];
    //weixinBtn.tag = UMSocialSnsTypeWechatSession;
    weixinBtn.layer.cornerRadius=25;
    weixinBtn=[self createButtonFrame:weixinBtn.frame backImageName:@"ic_landing_wechat" title:nil titleColor:nil font:nil target:self action:@selector(onClickWX:)];
    //qq
    QQBtn=[[UIButton alloc]initWithFrame:CGRectMake((self.view.frame.size.width-50)/2-100, 440, 50, 50)];
    //QQBtn.tag = UMSocialSnsTypeMobileQQ;
    QQBtn.layer.cornerRadius=25;
    QQBtn=[self createButtonFrame:QQBtn.frame backImageName:@"ic_landing_qq" title:nil titleColor:nil font:nil target:self action:@selector(onClickQQ:)];
    
    //新浪微博
    xinlangBtn=[[UIButton alloc]initWithFrame:CGRectMake((self.view.frame.size.width-50)/2+100, 440, 50, 50)];
    //xinlangBtn.tag = UMSocialSnsTypeSina;
    xinlangBtn.layer.cornerRadius=25;
    xinlangBtn=[self createButtonFrame:xinlangBtn.frame backImageName:@"ic_landing_microblog" title:nil titleColor:nil font:nil target:self action:@selector(onClickSina:)];
    
    [self.view addSubview:weixinBtn];
    [self.view addSubview:QQBtn];
    [self.view addSubview:xinlangBtn];
    [self.view addSubview:landBtn];
    //    [self.view addSubview:newUserBtn];
    //    [self.view addSubview:forgotPwdBtn];
}


- (void)onClickQQ:(UIButton *)button
{
}

- (void)onClickWX:(UIButton *)button
{
}


- (void)onClickSina:(UIButton *)button
{
    
}


-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField=[[UITextField alloc]initWithFrame:frame];
    
    textField.font=font;
    
    textField.textColor=[UIColor grayColor];
    
    textField.borderStyle=UITextBorderStyleNone;
    
    textField.placeholder=placeholder;
    
    return textField;
}

-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame];
    
    if (imageName)
    {
        imageView.image=[UIImage imageNamed:imageName];
    }
    if (color)
    {
        imageView.backgroundColor=color;
    }
    
    return imageView;
}

-(UIButton *)createButtonFrame:(CGRect)frame backImageName:(NSString *)imageName title:(NSString *)title titleColor:(UIColor *)color font:(UIFont *)font target:(id)target action:(SEL)action
{
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=frame;
    if (imageName)
    {
        [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    
    if (font)
    {
        btn.titleLabel.font=font;
    }
    
    if (title)
    {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    if (color)
    {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
    if (target&&action)
    {
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}


//登录
-(void)landClick
{
    if ([user.text isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"请输入用户名！"];
        return;
    }
    //    else if (user.text.length <11)
    //    {
    //        //[SVProgressHUD showInfoWithStatus:@"您输入的手机号码格式不正确"];
    //        return;
    //    }
    else if ([pwd.text isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"请输入密码！"];
        return;
    }
    else if (pwd.text.length <6)
    {
        [SVProgressHUD showInfoWithStatus:@"亲,密码长度至少六位"];
        return;
    }
    //    [self loginServer];
    [self loginOauth2];

}
-(void)loginOauth2{
    NSURL *url = [NSURL URLWithString:kBaseUrl];
    GROAuth2SessionManager *sessionManager = [GROAuth2SessionManager managerWithBaseURL:url clientID:@"clientTest" secret:@"123456"];
    
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [sessionManager authenticateUsingOAuthWithPath:@"auth/oauth/token"
                                          username:user.text
                                          password:pwd.text
                                             scope:@"email"
                                           success:^(AFOAuthCredential *credential) {
                                               NSLog(@"I have a token! %@", credential.accessToken);
                                               
                                               NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                                               NSString* password = [defaults objectForKey:@"loginuser"];
                                               if (password) {
                                                   if ([password isEqualToString:user.text]) {
                                                       [WorkOrderModelCopy clear];
                                                   }
                                                   else{
                                                       NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
                                                       [defaults1 removeObjectForKey:@"updatetime"];
                                                       [defaults1 synchronize];
                                                       //清工单数据
                                                       [WorkOrderModel clear];
                                                       [WorkOrderModelCopy clear];
                                                   }
                                               }
                                               
                                               
                                               [MySingleton sharedMySingleton].tokenID=credential.accessToken;
                                               [MySingleton sharedMySingleton].refreshToken=credential.refreshToken;
                                               //本地存token
                                               NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
                                               [defaults2 setObject:credential.accessToken forKey:@"accessToken"];
                                               [defaults2 setObject:credential.refreshToken forKey:@"refreshToken"];
                                               [defaults2 synchronize];
                                               
                                               [AFOAuthCredential storeCredential:credential withIdentifier:sessionManager.serviceProviderIdentifier];
                                               //
                                               [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                                               //                                               UIAlertController * alertCon = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"登录成功" preferredStyle:UIAlertControllerStyleAlert];
                                               //                                               UIAlertAction * action = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                               //
                                               //                                               }];
                                               //                                               [alertCon addAction:action];
                                               //                                               [self presentViewController:alertCon animated:YES completion:nil];
                                               //                                                [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录成功" withTime:0.5];
                                               //
                                               HomeViewController * homeVC = [[HomeViewController alloc]init];
                                               RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:homeVC];
                                               // 添加为子控制器
                                               nav.title = @"任务箱";
                                               [UIApplication sharedApplication].delegate.window.rootViewController=nav;
                                               
                                               [self postUI];
                                               [self postUIinfo];
                                               
                                               [defaults setObject:user.text forKey:@"loginuser"];
                                               [defaults synchronize];
                                           }
                                           failure:^(NSError *error) {
                                               NSLog(@"Error: %@", error);
                                               NSString* err=[error localizedDescription];
                                               if ([err containsString:@"400"]) {
                                                   [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                                                   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"用户不存在!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                                                   [alert show];
                                               }
                                               else{
                                                   [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
                                                   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"用户名或密码错误！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                                                   [alert show];
                                               }
                                           }];
}
//提交注册ID
-(void)postUI{
    if (![MySingleton sharedMySingleton].registrationID) {
        return;
    }
    NSDictionary *params = @{
                             @"loginMaching" : [MySingleton sharedMySingleton].registrationID
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool post:@"digiops/app/user/update" params:params success:^(id responseObj) {
        NSLog(@"");
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        rootViewController = nav;
    } failure:^(NSError *error) {
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
//获取用户信息
-(void)postUIinfo{
    NSDictionary *params = @{
                             @"access_token" : [MySingleton sharedMySingleton].tokenID
                             };
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:@"digiops/app/user/getUsers" params:params success:^(id responseObj) {
        NSLog(@"");
        if (responseObj[@"result"]==[NSNull null]) {
            return;
        }
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //角色
        UserRole* role=[UserRole mj_objectWithKeyValues:responseObj[@"result"][@"role"]];
        
        //用户
        UserInfo* user=[UserInfo mj_objectWithKeyValues:responseObj[@"result"]];
        //user share
        [UserInfo share].userNum=user.userNum;
        [UserInfo share].userName=user.userName;
        [UserInfo share].passWord=user.passWord;
        //权限
        NSArray* b=[user.role.menuRoleDTOs objectAtIndex:1];//权限取的临时任务
        MenuRole* m=[MenuRole mj_objectWithKeyValues:b];
        role.powerType=m.powerType;
        [UserInfo share].role=role;
        [UserInfo share].roleName=user.roleName;
        [UserInfo share].telephone=user.telephone;
        [UserInfo share].sites=user.sites;
        [UserInfo share].uuid=user.uuid;
        
        //站点
        //        for (NSDictionary* site in self.user.sites) {
        //            UserSites* s=[UserSites mj_objectWithKeyValues:site];
        //            NSLog(@"");
        //        }
        NSLog(@"");
        [self offline];
        
        //        rootViewController = nav;
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
-(void)loginServer{
    //    NSDictionary *params = @{
    //                             @"username" : _loginText.text,
    //                             @"password" : _passwdText.text
    //                             };
    NSDictionary *params = @{
                             @"grant_type" : @"password",
                             @"username" : @"666666",
                             @"password" : @"666666"
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool post:@"oauth/token" params:params success:^(id responseObj) {
        NSLog(@"");
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        UIAlertController * alertCon = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"登录成功" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertCon addAction:action];
        [self presentViewController:alertCon animated:YES completion:nil];
        
        HomeViewController * homeVC = [[HomeViewController alloc]init];
        RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:homeVC];
        // 添加为子控制器
        nav.title = @"任务箱";
        [UIApplication sharedApplication].delegate.window.rootViewController=nav;
        //        rootViewController = nav;
    } failure:^(NSError *error) {
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        UIAlertController * alertCon = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"登录成功" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertCon addAction:action];
        [self presentViewController:alertCon animated:YES completion:nil];
        
        HomeViewController * homeVC = [[HomeViewController alloc]init];
        RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:homeVC];
        // 添加为子控制器
        nav.title = @"任务箱";
        
        [UIApplication sharedApplication].delegate.window.rootViewController=nav;
    }];
}

//注册
-(void)zhuce
{
    //    [self.navigationController pushViewController:[[MMZCHMViewController alloc]init] animated:YES];
}

-(void)registration:(UIButton *)button
{
    //   [self.navigationController pushViewController:[[MMZCHMViewController alloc]init] animated:YES];
}

-(void)fogetPwd:(UIButton *)button
{
    //   [self.navigationController pushViewController:[[forgetPassWardViewController alloc]init] animated:YES];
}

#pragma mark - 工具
//手机号格式化
-(NSString*)getHiddenStringWithPhoneNumber:(NSString*)number middle:(NSInteger)countHiiden{
    // if (number.length>6) {
    
    if (number.length<countHiiden) {
        return number;
    }
    NSInteger count=countHiiden;
    NSInteger leftCount=number.length/2-count/2;
    NSString *xings=@"";
    for (int i=0; i<count; i++) {
        xings=[NSString stringWithFormat:@"%@%@",xings,@"*"];
    }
    
    NSString *chuLi=[number stringByReplacingCharactersInRange:NSMakeRange(leftCount, count) withString:xings];
    // chuLi=[chuLi stringByReplacingCharactersInRange:NSMakeRange(number.length-count, count-leftCount) withString:xings];
    
    return chuLi;
}

//手机号格式化后还原
-(NSString*)getHiddenStringWithPhoneNumber1:(NSString*)number middle:(NSInteger)countHiiden{
    // if (number.length>6) {
    if (number.length<countHiiden) {
        return number;
    }
    NSString *xings=@"";
    for (int i=0; i<1; i++) {
        //xings=[NSString stringWithFormat:@"%@",[CheckTools getUser]];
    }
    
    NSString *chuLi=[number stringByReplacingCharactersInRange:NSMakeRange(0, 0) withString:@""];
    // chuLi=[chuLi stringByReplacingCharactersInRange:NSMakeRange(number.length-count, count-leftCount) withString:xings];
    
    return chuLi;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)offline
{
    [AuditCategoryOffline clear];
    [LineDetailOffline clear];
    [PointModelOffline clear];
    
    [self postofflineRouteUI];
    [self postofflineSopUI];
    [self postofflineShiftUI];
    [self postofflineAuditUI];
    [self postofflineAuditGeneralUI];
}
-(void)postofflineRouteUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    NSDictionary *params = @{
                             @"siteUuid" : s.uuid
                             };
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:[NSString stringWithFormat:@"digiops/app/SelectLineRecords"] params:nil success:^(id responseObj) {
        NSLog(@"");
        
        for (NSDictionary* route in responseObj[@"content"]) {
            RouteModel* r=[RouteModel mj_objectWithKeyValues:route];
            
            //离线存储
            for (NSDictionary* line in r.details) {
                LineDetailOffline* l=[LineDetailOffline mj_objectWithKeyValues:line];
                //lineUuid居然在上面一级的model里面
                l.lineUuid=r.uuid;
                //不知这里为啥用了linedetail的uuid
                l.offlineuuid=r.uuid;
                l.routeModelc=r;
                [l saveOrUpdateAsync:^(BOOL isSuccess) {
                    
                }];
                NSLog(@"");
            }
            
        }
        
        NSLog(@"");
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
-(void)postofflineSopUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    //离线调用去掉餐宿
    //    NSDictionary *params = @{
    //                             @"siteUuid" : self.line.pointUuid
    //                             };
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:[NSString stringWithFormat:@"digiops/app/SelectPoints"] params:nil success:^(id responseObj) {
        NSLog(@"");
        
        //离线存储
        for (NSDictionary* sop in responseObj[@"content"]) {
            SopModel* s=[SopModel mj_objectWithKeyValues:sop];
            
            for (NSDictionary* temp in s.sopTemplates) {
                
                PointModelOffline* p=[PointModelOffline mj_objectWithKeyValues:temp];
                
                NSData *data = [p.content dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray* arr=[NSMutableArray new];
                for (NSDictionary* v in dict) {
                    PointValueModel* model=[PointValueModel mj_objectWithKeyValues:v];
                    [arr addObject:model];
                    
                }
                p.valueArr=arr;
                p.sopUuid=s.uuid;
                p.offlineuuid=s.pointNum;
                p.pointNum=s.pointNum;
                p.pointUuid=s.pointUuid;//pointuuid为了多个工单问题
                //
                p.offlineName=s.sopName;
                [p saveOrUpdateAsync:^(BOOL isSuccess) {
                    
                }];
                NSLog(@"");
            }
            NSLog(@"");
            
        }
        NSLog(@"");
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
-(void)postofflineShiftUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    NSDictionary *params = @{
                             @"siteUuid" : s.uuid
                             };
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:[NSString stringWithFormat:@"digiops/app/SelectShifts"] params:nil success:^(id responseObj) {
        NSLog(@"");
        
        //离线存储
        for (NSDictionary* shift in responseObj[@"content"]) {
            ShiftModel* a=[ShiftModel mj_objectWithKeyValues:shift];
            
            for (NSDictionary* template in a.shiftTemplates) {
                
                PointModelOffline* p=[PointModelOffline mj_objectWithKeyValues:template];
                
                NSData *data = [p.content dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray* arr=[NSMutableArray new];
                for (NSDictionary* v in dict) {
                    PointValueModel* model=[PointValueModel mj_objectWithKeyValues:v];
                    [arr addObject:model];
                    
                }
                p.valueArr=arr;
                NSLog(@"");
                p.shiftUuid=a.uuid;
                p.uuid=a.uuid;
                
                p.offlineuuid=a.uuid;
                p.pointNum=a.uuid;
                p.offlineName=a.shiftName;
                [p saveOrUpdateAsync:^(BOOL isSuccess) {
                    
                }];
                NSLog(@"");
            }
            NSLog(@"");
            
        }
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
-(void)postofflineAuditUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    NSDictionary *params = @{
                             @"siteUuid" : s.uuid
                             };
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:[NSString stringWithFormat:@"digiops/app/SelectAudits"] params:nil success:^(id responseObj) {
        NSLog(@"");
        
        //
        for (NSDictionary* audit in responseObj[@"content"]) {
            AuditModel* a=[AuditModel mj_objectWithKeyValues:audit];
            //amodel取不到问题
            [a saveOrUpdateAsync:^(BOOL isSuccess) {
                
            }];
            for (NSDictionary* template in a.category) {
                AuditCategoryOffline* cat=[AuditCategoryOffline mj_objectWithKeyValues:template];
                //
                cat.offlineuuid=a.uuid;
                [cat saveOrUpdateAsync:^(BOOL isSuccess) {
                    
                }];
            }
            NSLog(@"");
        }
        
        
        NSLog(@"");
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
-(void)postofflineAuditGeneralUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    NSDictionary *params = @{
                             @"siteUuid" : s.uuid
                             };
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:[NSString stringWithFormat:@"digiops/app/SelectAudits"] params:nil success:^(id responseObj) {
        NSLog(@"");
        
        //离线存储
        for (NSDictionary* audit in responseObj[@"content"]) {
            AuditModel* a=[AuditModel mj_objectWithKeyValues:audit];
            
            for (NSDictionary* template in a.category) {
                AuditCategory* cat=[AuditCategory mj_objectWithKeyValues:template];
                for (NSDictionary* category in cat.category) {
                    PointModelOffline* p=[PointModelOffline mj_objectWithKeyValues:category];
                    
                    p.auditUuid=a.uuid;
                    if (p.content) {
                        
                        NSData *data = [p.content dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                        NSMutableArray* arr=[NSMutableArray new];
                        for (NSDictionary* v in dict) {
                            PointValueModel* model=[PointValueModel mj_objectWithKeyValues:v];
                            [arr addObject:model];
                            
                        }
                        p.valueArr=arr;
                    }
                    
                    //                    _auditUuid=a.uuid;
                    p.auditUuid=a.uuid;
                    p.offlineuuid=a.uuid;
                    p.pointNum=a.uuid;
                    
                    [p saveOrUpdateAsync:^(BOOL isSuccess) {
                        
                    }];
                    NSLog(@"");
                }
            }
            NSLog(@"");
            
        }
        
        NSLog(@"");
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
@end
